package com.shang.sync.suanfa;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Test {


    public static void main(String args[]){
        Test test = new Test();
        int[] nums = {2,3,4,5,6,7,8,9};
//        int[] ints = test.twoSum(nums, 9);
        int[] ints = test.twoSum2(nums, 9);
//        int[] ints = test.twoSumHash(nums, 9);
        System.out.println(ints.length);
    }



    public int[] twoSum(int[] nums, int target) {

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }

        return new int[0];
    }

    public int[] twoSumHash(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<Integer, Integer>(nums.length - 1);
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])){
                return new int[]{map.get(target - nums[i]),i};
            }
            map.put(nums[i],i);
        }
        return new int[0];
    }

    public int[] twoSum2(int[] nums, int target) {

        int[] tmp=new int[nums.length];
        System.arraycopy(nums,0,tmp,0,nums.length);
        Arrays.sort(nums);

        for(int i=0,j=nums.length-1;i<j;){
            if(nums[i]+nums[j]<target)
                i++;
            else if(nums[i]+nums[j]>target)
                j--;
            else if(nums[i]+nums[j]==target){
                return new int[]{i,j};
            }
        }
        return new int[0];
    }
}
